<template>
  <div class="change_password">
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-2 col-md-offset-5 col-xs-6 col-xs-offset-3">
          <img src="../../assets/logo1.png" class="text-center" style="width: 50%;margin: 25% 25% 0 25%;">
          <h3 class="text-center">修改密码</h3>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6 col-md-offset-3">
          <van-form @submit="onSubmit" >
            <van-field
                v-model="oldpassword"
                name="旧密码"
                label="旧密码"
                placeholder="旧密码"
                :rules="[{ pattern: passwordpattern,required: true, message: '请输入6-10位由大小写字母、数字组成的密码' }]"
            />
            <van-field
                v-model="newpassword"
                name="密码"
                label="密码"
                placeholder="密码"
                type="password"
                :rules="[{ pattern: passwordpattern,required: true, message: '请输入6-10位由大小写字母、数字组成的密码' }]"
            />
            <van-field
                v-model="againpassword"
                name="确认密码"
                label="确认密码"
                placeholder="再次输入密码"
                type="password"
                :rules="[{ validator:yzmmm,required: true, message: '两次密码输入不一样' }]"
            />
            <div style="margin: 16px;">
              <van-button block round size="large" type="info" native-type="submit">修改</van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import {setUserPwd} from "../../utils/api";

export default {
  name: "ChangePassword",
  data(){
    return {
      oldpassword:'',
      newpassword:'',
      againpassword:'',
      passwordpattern:/^[0-9a-zA-Z]{6,10}$/
    }
  },
  methods:{
    onSubmit(){
      if(this.oldpassword && this.newpassword &&this.$store.state.userid){
        setUserPwd(qs.stringify({oldpassword:this.oldpassword,id:this.$store.state.userid,newpassword:this.newpassword})).then(respose=>{
          if(respose.status===200){
            this.$message.success("修改密码成功")
            this.$router.go(-1);
            this.$router.replace("/");
          }else{
            this.$message.error("旧密码错误")
          }
        }).catch(error=>{
          console.log(error);
          this.$message.error("出现未知错误，请联系管理员")
        })
      }else{
        this.$message.error("密码未填写或请刷新尝试")
      }
    },
    yzmmm(){
      return this.newpassword === this.againpassword;
    },
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例
      let id =vm.$store.state.userid;
      if(!id){
        vm.$message.error("请先登录")
        vm.$router.go(-1);
        vm.$router.replace("/")
      }
    })
  }
}
</script>

<style scoped>

</style>
